import React, {useContext, useRef} from 'react';
import {View, ScrollView, Alert} from 'react-native';
import Toast from 'react-native-root-toast';
import {useMount, useSafeState, useSetState} from 'ahooks';
import {useNavigation} from '@react-navigation/native';
import {Text, Button, Tab, Header, Input, CheckBox} from '@rneui/base';
import FontAwesome6 from 'react-native-vector-icons/FontAwesome6';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {useSelector, useDispatch} from 'react-redux';
import GlobalContext from '@/GlobalContext';
import {setAccountInfo, setToken} from '@/store';
import {ApiHost} from '@/config/common';
import style from './style.less';

export default ({}) => {
  const dispatch = useDispatch();

  const navigation = useNavigation();
  const [state, setState] = useSetState({});
  const [account, setAccount] = useSafeState('zhangyp001');
  const [pwd, setPwd] = useSafeState('123456');
  const [showPwd, setShowPwd] = useSafeState(false);
  const [agreeTerm, setAgreeTerm] = useSafeState(true);

  const isAllowSubmit = account && pwd && agreeTerm;

  const refAccount = useRef();

  const DelIcon = () => {
    if (account.length > 0) {
      return (
        <FontAwesome6
          name="xmark"
          size={24}
          onPress={() => {
            refAccount.current.clear();
            setAccount('');
          }}
        />
      );
    } else {
      return <></>;
    }
  };

  const refPwd = useRef();
  const EyeIcon = () => {
    if (pwd.length > 0) {
      return (
        <FontAwesome6
          name="eye"
          size={24}
          onPress={e => {
            setShowPwd(!showPwd);
            e.stopPropagation();
          }}
          color={showPwd ? '#333' : '#999'}
        />
      );
    } else {
      return <></>;
    }
  };

  const [submitLoading, setSubmitLoading] = useSafeState(false);
  const submit = async () => {
    setSubmitLoading(true);
    try {
      let rsObj = undefined;
      try {
        const reqFormData = {
          c_loginname: account,
          c_password: pwd,
        };
        let res = await fetch(`${ApiHost}/account/json/login`, {
          headers: {
            'content-type': 'application/json',
          },
          method: 'POST',
          body: JSON.stringify(reqFormData),
        });
        rsObj = await res.json();
        setSubmitLoading(false);
      } catch (e) {
        setSubmitLoading(false);
        Alert.alert('操作失败', e.message);
        return;
      }
      if (!rsObj) {
        Alert.alert('操作失败', '!rsObj');
        return;
      }
      const {code = 0, msg, account_info, token, token_info} = rsObj || {};
      if (code <= 0) {
        Alert.alert('操作失败', msg);
        return;
      }

      AsyncStorage.setItem('token', token);
      AsyncStorage.setItem('tokenInfo', JSON.stringify(token_info));
      AsyncStorage.setItem('accountInfo', JSON.stringify(account_info));
      dispatch(setAccountInfo(account_info));

      dispatch(setToken(token));

      setTimeout(function () {
        navigation.goBack();
      }, 300);
      let toast = Toast.show('密码正确，登录成功！', {
        // duration: Toast.durations.LONG,
        duration: 1000,
        // position: Toast.positions.CENTER,
        position: 150,
        shadow: true,
        animation: true,
        hideOnPress: true,
        delay: 0,
        onShow: () => {
          // calls on toast\`s appear animation start
        },
        onShown: () => {
          // calls on toast\`s appear animation end.
        },
        onHide: () => {
          // calls on toast\`s hide animation start.
        },
        onHidden: () => {
          // calls on toast\`s hide animation end.
        },
      });
      // setTimeout(function () {
      //   Toast.hide(toast);
      // }, 1000);
    } catch (e) {
      Alert.alert('系统繁忙', '操作失败');
    }
  };

  return (
    <View style={style.box}>
      <View style={style.back}>
        <FontAwesome6
          name="angles-left"
          size={24}
          onPress={() => {
            navigation.goBack();
          }}
        />
      </View>
      <ScrollView style={style.scroView}>
        <View style={style.tab}>
          <Text h4>账号密码登录</Text>
        </View>
        <View style={style.form}>
          <Input
            ref={refAccount}
            defaultValue={account}
            onChangeText={setAccount}
            placeholder="帐号"
            maxLength={50}
            leftIcon={<FontAwesome6 name="user" size={20} />}
            rightIcon={<DelIcon />}
          />
          <Input
            ref={refPwd}
            defaultValue={pwd}
            onChangeText={setPwd}
            placeholder="密码"
            secureTextEntry={!showPwd}
            maxLength={50}
            leftIcon={<FontAwesome6 name="key" size={20} />}
            rightIcon={<EyeIcon />}
          />
        </View>
        <View style={style.btnBox}>
          <Button
            radius={10}
            disabled={!isAllowSubmit}
            loading={submitLoading}
            onPress={submit}>
            登录
          </Button>
        </View>
        <View style={style.otherNav}>
          <Text>忘记密码</Text>
          <Text>新账户注册</Text>
        </View>
        <View style={style.agreeBox}>
          <CheckBox
            checked={!!agreeTerm}
            title="同意"
            onPress={() => setAgreeTerm(!agreeTerm)}
            containerStyle={{
              paddingLeft: 0,
              paddingRight: 0,
              marginLeft: 0,
              marginRight: 0,
            }}
          />
          <Text style={{padding: 0, margin: 0}}>《账户注册隐私政策》</Text>
        </View>
      </ScrollView>
    </View>
  );
};
